<template>
  <el-container>
    <el-header>
      <h1>设备列表</h1>
      <el-button type="primary" @click="goToAddDevice">添加设备</el-button>
    </el-header>
    <el-main>
      <el-table :data="devices" style="width: 100%">
        <el-table-column prop="id" label="ID" width="100" />
        <el-table-column prop="name" label="设备名称" />
        <el-table-column prop="location" label="设备位置" />
        <el-table-column prop="status" label="设备状态" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editDevice(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteDevice(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
  </el-container>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  computed: {
    ...mapState(['devices']),
  },
  methods: {
    ...mapActions(['fetchDevices']),
    goToAddDevice() {
      this.$router.push('/devices/add');
    },
    editDevice(device) {
      this.$router.push(`/devices/edit/${device.id}`);
    },
    async deleteDevice(id) {
      await this.$api.deleteDevice(id);
      this.fetchDevices();
    },
  },
  mounted() {
    this.fetchDevices();
  },
};
</script>